package com.example.demo.common;


import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created realshare
 * author:fh
 * Date:2019/4/23
 * Time:9:57
 * desc:切面编程 用于打印输入输出
 **/
@Aspect // 定义一个切面
@Configuration
public class LogRecordAspect {
    private static Log logger = LogFactory.getLog(LogRecordAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.example.demo.controller.*.*Controller.*(..))")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String method = request.getMethod();
        String uri = request.getRequestURI();
        String paraString = JSON.toJSONString(request.getParameterMap());
        logger.info("*****************************************");
        logger.info("请求开始, URI: {" + uri + "}," +
                " method: {" + method + "}, " +
                "params: {" + paraString + "}");
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        logger.info("请求结束，controller的返回值是 " + JSON.toJSONString(result));
        logger.info("******************************************");

        return result;
    }
}


